package com.itggm.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itggm.Result.ResponseResult;
import com.itggm.dto.StudentPageDTO;
import com.itggm.exception.BusinessException;
import com.itggm.mapper.CourseMapper;
import com.itggm.pojo.Course;
import com.itggm.pojo.Student;
import com.itggm.service.StudentService;
import com.itggm.mapper.StudentMapper;
import com.itggm.vo.StudentVO;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
* @author root
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2024-12-27 16:45:49
*/
@Service
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private CourseMapper courseMapper;

    @Override
    public ResponseResult studentList(StudentPageDTO studentPageDTO) {
        //新建分页对象
        Page<Student> studentPage = new Page<>(studentPageDTO.getPage(),studentPageDTO.getLimit());
        String studentNo = studentPageDTO.getStudentNo();
        String clazz = studentPageDTO.getClazz();
        //构建分页条件
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz).orderByDesc(Student::getSchoolYear);
        //执行分页
        studentMapper.selectPage(studentPage, wrapper);
        //封装返回结果
        List<Student> students = studentPage.getRecords();
        if (ObjectUtils.isEmpty(students)) {
            throw new BusinessException("没有找到学生记录");
        }

        List<StudentVO> studentVOList = new ArrayList<>();
        for (Student student : students) {
            StudentVO studentVO = new StudentVO();
            BeanUtils.copyProperties(student, studentVO);
            Course course = courseMapper.selectById(student.getCourseId()); // 假设课程ID是 student.getCourseId()
            if (course != null) {
                studentVO.setCourseName(course.getCourseName());
            } else {
                studentVO.setCourseName("未知课程");
            }
            studentVOList.add(studentVO);
        }

        return ResponseResult.success()
                .data("tableData", studentVOList)
                .data("total", studentPage.getTotal());
    }

    @Override
    public ResponseResult importStudent(MultipartFile file) {
       //先判断文件是否为空
        if (ObjectUtils.isEmpty(file)) {
            throw new BusinessException("文件为空");
        }
        // 创建一个导入参数对象
        ImportParams importParams = new ImportParams();
        // 表头占据的行数
        importParams.setHeadRows(1);
        // 标题占据的行数
        importParams.setTitleRows(1);
        // 解析excel中的数据
        try {
            InputStream inputStream = file.getInputStream();
            List<Student> students= ExcelImportUtil.importExcel(inputStream, Student.class, importParams);
            System.out.println("students"+students);

            students.forEach(student -> {
                try {
                    baseMapper.insert(student);
                }catch (DuplicateKeyException e){
                    throw  new BusinessException("学号"+student.getStudentNo()+"重复");
                }
            });
            return ResponseResult.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void exportStudent(String studentNo, String clazz, HttpServletResponse response) {
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz);
        List<Student> students = baseMapper.selectList(lambda);

        // 创建导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生信息表");
        exportParams.setSheetName("学生信息表1");
        // 工作簿对象
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, students);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}


